<?php
/**
 * Created by PhpStorm.
 * User: zouyanan
 * Date: 2019/5/11
 * Time: 下午10:35
 */

namespace app\api\controller;
use app\common\controller\Api;
use think\Exception;
use fast\Random;
use think\Validate;
use app\common\library\Token;


class Login extends Api
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';


    public function login()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        ob_clean();
        $user = db('user');
        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');
        if(!$mobile || !$password){
            $this->error('缺少参数');
        }
        $user_info = $user->field("id,password,salt")->where('mobile',$mobile)->find();
        if(!$user_info){
            $this->error('未找到该用户');
        }
        if($user_info['password'] != $this->auth->getEncryptPassword($password,$user_info['salt'])){
            $this->error('密码错误');
        }
        $res = $this->auth->direct($user_info['id']);
        if ($res) {
            $this->success('登录成功',['token'=>$this->auth->getToken()]);
        } else {
            $this->error('登录失败');
        }
    }




    /**
     * 短信验证码
     */
    public function smsCode()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        $mobile = $this->request->request('mobile');
        $type = $this->request->request('type'); //1注册， 2登录， 3修改密码, 4实名认证
        if (!$mobile) {
            $this->error('请填写手机号');
        }
        if (!$type) {
            $this->error('参数错误');
        }
        $info = db('telcode')->where('ext', $type)->where('tel', $mobile)->find();
        if ($info && $info['expiretime'] > time()) {
            $code = $info['code'];
        } else {
            db('telcode')->where('ext', $type)->where('tel', $mobile)->delete();
            $code = mt_rand(100000,999999);
        }

        $sms = new \sms\ChuanglanSmsHelper\ChuanglanSmsApi();
        $result = $sms->sendSMS($mobile,'【253云通讯】您好，您的验证码是：' . $code );
        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                $info = db('telcode')->where('ext', $type)->where('tel', $mobile)->find();
                if (!$info) {
                    $res = db('telcode')->insertGetId(['tel' => $mobile, 'ext' => $type, 'code' => $code, 'expiretime' => time() + 180]);
                } 
                $this->success('success');
            }else{
                $this->error($output['errorMsg']);
            }
        }else{
                $this->error($result); 
        }
    }

    /**
     * 核验验证码
     */
     protected function checkCode($mobile, $code, $type = 1){
         header('Access-Control-Allow-Origin: *');
         header('Access-Control-Allow-Credentials: true');
         header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
         header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        switch ($type) {
            case 1:
                $map['ext'] = 1;
                break;
            case 2:
                $map['ext'] = 2;
                break;
            case 3:
                $map['ext'] = 3;
				break;
			case 4:
			   	$map['ext'] = 4;
				break;
            default:
                $map['ext'] = 1;
                break;
        }
		
        $map['tel'] = $mobile;
        $info = db('telcode')->field("*")->where($map)->find();
        if (!$info) {
            return 0;
		}
		
        if (($code != $info['code']) || ($info['expiretime'] <= time())) {
            db('telcode')->where('tel', $mobile)->delete();
            return 0;
        }
        db('telcode')->where('tel', $mobile)->delete();
        db('telcode')->where('expiretime', '<=', time())->delete();
       return 1;

    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        $mobile = $this->request->request("mobile");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("code");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('Users not found'));
        }
        $ret = $this->checkCode($mobile, $captcha, 3);
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    //退出登录
    public function loginout(){


    }









}